package com.hands.netty.netty;



import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Title: NioServer
 * @Description: nio服务端
 * @date
 */

@Service
public class NioServer implements CommandLineRunner {

    //  private static final Logger logger = LoggerFactory.getLogger(NioServer.class);
    //连接map
    public  static Map<String, ChannelHandlerContext> map = new HashMap<String, ChannelHandlerContext>();
    //默认端口
    private static Integer defaultPort=8866;
    public void bind(Integer port) throws Exception {
        //配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 1024, 65536))//固定大小的接受缓冲区分配器
                    .option(ChannelOption.SO_SNDBUF, 20*1024*1024)//发送缓冲区的大小
                    .option(ChannelOption.SO_RCVBUF, 20*1024*1024)//接收缓冲区的大小
                    .option(ChannelOption.SO_BACKLOG, 128)//用来初始化服务端可连接队列
                    .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1,1024*1024*8))
                    .option(ChannelOption.SO_KEEPALIVE, true) // 2小时无数据激活心跳机制
                    .childHandler(new ServerChannelInitializer());
            // 服务器异步创建绑定
            if(null==port){
                port=this.defaultPort;
            }
            ChannelFuture f = b.bind(port).sync();
               //log.info("服务启动：{}"+ new Date());
            // 关闭服务器通道
            f.channel().closeFuture().sync();
        } finally {
            //  logger.info("服务停止："+ DateUtils.dateToString(new Date()));
            // 释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

//    public static void main(String[] args) {
//        new Thread(() -> {
//            try {
//                new NioServer().bind(defaultPort);
//            } catch (Exception e) {
//                e.printStackTrace();
//
//            }
//        }).start();
//    }

    public void start(){
        new Thread(() -> {
            try {
               // log.info("TCP启动端口8000");
                new NioServer().bind(defaultPort);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }).start();
    }



    @Override
    public void run(String... args) throws Exception {
        this.start();
    }
}